﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Windows.Media.Effects;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using VMuktiGrid.CustomMenu;
using VMukti.Presentation.Controls;
//using VMukti.Presentation.Page_Tab;
using System.Collections.Generic;
using VMukti.Business.CommonDataContracts;
using VMuktiAPI;

namespace VMuktiGrid.ctlPage
{
    [TemplatePart(Name = "PART_DropDown", Type = typeof(ToggleButton))]
    [TemplatePart(Name = "PART_RepeatLeft", Type = typeof(RepeatButton))]
    [TemplatePart(Name = "PART_RepeatRight", Type = typeof(RepeatButton))]
    [TemplatePart(Name = "PART_NewTabButton", Type = typeof(ButtonBase))]
    [TemplatePart(Name = "PART_ScrollViewer", Type = typeof(ScrollViewer))]
    public class TabControl : System.Windows.Controls.TabControl
    {
        // public Events
        public event EventHandler<TabItemEventArgs> TabItemAdded;
        public event EventHandler<TabItemCancelEventArgs> TabItemClosing;
        public event EventHandler<TabItemEventArgs> TabItemClosed;

        // TemplatePart controls
        private ToggleButton _toggleButton;

        static TabControl()
        {
            try
            {
                DefaultStyleKeyProperty.OverrideMetadata(typeof(TabControl), new FrameworkPropertyMetadata(typeof(TabControl)));

                TabStripPlacementProperty.AddOwner(typeof(TabControl), new FrameworkPropertyMetadata(Dock.Top, new PropertyChangedCallback(OnTabStripPlacementChanged)));
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "TabControl()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        /// <summary>
        /// OnTabStripPlacementChanged property callback
        /// </summary>
        /// <remarks>
        ///     We need to supplement the base implementation with this method as the base method does not work when
        ///     we are using virtualization in the tabpanel, it only updates visible items
        /// </remarks>
        private static void OnTabStripPlacementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                TabControl tc = (TabControl)d;

                foreach (TabItem item in tc.Items)
                    item.CoerceValue(TabItem.TabStripPlacementProperty);
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "OnTabStripPlacementChanged()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        #region Dependancy properties

        #region Brushes

        public Brush pgTabItemNormalBackground
        {
            get { return (Brush)GetValue(pgTabItemNormalBackgroundProperty); }
            set { SetValue(pgTabItemNormalBackgroundProperty, value); }
        }
        public static readonly DependencyProperty pgTabItemNormalBackgroundProperty = DependencyProperty.Register("pgTabItemNormalBackground", typeof(Brush), typeof(TabControl), new UIPropertyMetadata(null));

        public Brush pgTabItemMouseOverBackground
        {
            get { return (Brush)GetValue(pgTabItemMouseOverBackgroundProperty); }
            set { SetValue(pgTabItemMouseOverBackgroundProperty, value); }
        }
        public static readonly DependencyProperty pgTabItemMouseOverBackgroundProperty = DependencyProperty.Register("pgTabItemMouseOverBackground", typeof(Brush), typeof(TabControl), new UIPropertyMetadata(null));

        public Brush pgTabItemSelectedBackground
        {
            get { return (Brush)GetValue(pgTabItemSelectedBackgroundProperty); }
            set { SetValue(pgTabItemSelectedBackgroundProperty, value); }
        }
        public static readonly DependencyProperty pgTabItemSelectedBackgroundProperty = DependencyProperty.Register("pgTabItemSelectedBackground", typeof(Brush), typeof(TabControl), new UIPropertyMetadata(null));

        #endregion

        /*
         * Based on the whether the ControlTemplate implements the NewTab button and Close Buttons determines the functionality of the AllowAddNew & AllowDelete properties
         * If they are in the control template, then the visibility of the AddNew & TabItem buttons are bound to these properties
         * 
        */
        /// <summary>
        /// Allow the User to Add New TabItems
        /// </summary>
        public bool AllowAddNew
        {
            get { return (bool)GetValue(AllowAddNewProperty); }
            set { SetValue(AllowAddNewProperty, value); }
        }
        public static readonly DependencyProperty AllowAddNewProperty = DependencyProperty.Register("AllowAddNew", typeof(bool), typeof(TabControl), new UIPropertyMetadata(true));

        /// <summary>
        /// Allow the User to Delete TabItems
        /// </summary>
        public bool AllowDelete
        {
            get { return (bool)GetValue(AllowDeleteProperty); }
            set { SetValue(AllowDeleteProperty, value); }
        }
        public static readonly DependencyProperty AllowDeleteProperty = DependencyProperty.Register("AllowDelete", typeof(bool), typeof(TabControl),
            new FrameworkPropertyMetadata(true, new PropertyChangedCallback(OnAllowDeleteChanged)));

        private static void OnAllowDeleteChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TabControl tc = (TabControl)d;
            foreach (TabItem item in tc.Items)
                item.AllowDelete = (bool)e.NewValue;
        }

        /// <summary>
        /// Set new TabItem as the current selection
        /// </summary>
        public bool SelectNewTabOnCreate
        {
            get { return (bool)GetValue(SelectNewTabOnCreateProperty); }
            set { SetValue(SelectNewTabOnCreateProperty, value); }
        }
        public static readonly DependencyProperty SelectNewTabOnCreateProperty = DependencyProperty.Register("SelectNewTabOnCreate", typeof(bool), typeof(TabControl), new UIPropertyMetadata(true));


        /// <summary>
        /// Determines where new TabItems are added to the TabControl
        /// </summary>
        /// <remarks>
        ///     Set to true (default) to add all new Tabs to the end of the TabControl
        ///     Set to False to insert new tabs after the current selection
        /// </remarks>
        public bool AddNewTabToEnd
        {
            get { return (bool)GetValue(AddNewTabToEndProperty); }
            set { SetValue(AddNewTabToEndProperty, value); }
        }
        public static readonly DependencyProperty AddNewTabToEndProperty = DependencyProperty.Register("AddNewTabToEnd", typeof(bool), typeof(TabControl), new UIPropertyMetadata(true));

        /// <summary>
        /// defines the Minimum width of a TabItem
        /// </summary>
        [DefaultValue(80)]
        [Category("Layout")]
        [Description("Gets or Sets the minimum Width Constraint shared by all Items in the Control, individual child elements MinWidth property will overide this property")]
        public double TabItemMinWidth
        {
            get { return (double)GetValue(TabItemMinWidthProperty); }
            set { SetValue(TabItemMinWidthProperty, value); }
        }
        public static readonly DependencyProperty TabItemMinWidthProperty = DependencyProperty.Register("TabItemMinWidth", typeof(double), typeof(TabControl),
            new FrameworkPropertyMetadata(80.0, new PropertyChangedCallback(OnMinMaxChanged), new CoerceValueCallback(CoerceMinWidth)));

        private static object CoerceMinWidth(DependencyObject d, object value)
        {
            TabControl tc = (TabControl)d;
            double newValue = (double)value;

            if (newValue > tc.TabItemMaxWidth)
                return tc.TabItemMaxWidth;

            return (newValue > 0 ? newValue : 0);
        }

        /// <summary>
        /// defines the Minimum height of a TabItem
        /// </summary>
        [DefaultValue(20)]
        [Category("Layout")]
        [Description("Gets or Sets the minimum Height Constraint shared by all Items in the Control, individual child elements MinHeight property will override this value")]
        public double TabItemMinHeight
        {
            get { return (double)GetValue(TabItemMinHeightProperty); }
            set { SetValue(TabItemMinHeightProperty, value); }
        }
        public static readonly DependencyProperty TabItemMinHeightProperty = DependencyProperty.Register("TabItemMinHeight", typeof(double), typeof(TabControl),
            new FrameworkPropertyMetadata(30.0, new PropertyChangedCallback(OnMinMaxChanged), new CoerceValueCallback(CoerceMinHeight)));

        private static object CoerceMinHeight(DependencyObject d, object value)
        {
            TabControl tc = (TabControl)d;
            double newValue = (double)value;

            if (newValue > tc.TabItemMaxHeight)
                return tc.TabItemMaxHeight;

            return (newValue > 0 ? newValue : 0);
        }

        /// <summary>
        /// defines the Maximum width of a TabItem
        /// </summary>
        [DefaultValue(double.PositiveInfinity)]
        [Category("Layout")]
        [Description("Gets or Sets the maximum width Constraint shared by all Items in the Control, individual child elements MaxWidth property will override this value")]
        public double TabItemMaxWidth
        {
            get { return (double)GetValue(TabItemMaxWidthProperty); }
            set { SetValue(TabItemMaxWidthProperty, value); }
        }
        public static readonly DependencyProperty TabItemMaxWidthProperty = DependencyProperty.Register("TabItemMaxWidth", typeof(double), typeof(TabControl),
            new FrameworkPropertyMetadata(double.PositiveInfinity, new PropertyChangedCallback(OnMinMaxChanged), new CoerceValueCallback(CoerceMaxWidth)));

        private static object CoerceMaxWidth(DependencyObject d, object value)
        {
            TabControl tc = (TabControl)d;
            double newValue = (double)value;

            if (newValue < tc.TabItemMinWidth)
                return tc.TabItemMinWidth;

            return newValue;
        }

        /// <summary>
        /// defines the Maximum width of a TabItem
        /// </summary>
        [DefaultValue(double.PositiveInfinity)]
        [Category("Layout")]
        [Description("Gets or Sets the maximum height Constraint shared by all Items in the Control, individual child elements MaxHeight property will override this value")]
        public double TabItemMaxHeight
        {
            get { return (double)GetValue(TabItemMaxHeightProperty); }
            set { SetValue(TabItemMaxHeightProperty, value); }
        }
        public static readonly DependencyProperty TabItemMaxHeightProperty = DependencyProperty.Register("TabItemMaxHeight", typeof(double), typeof(TabControl),
            new FrameworkPropertyMetadata(double.PositiveInfinity, new PropertyChangedCallback(OnMinMaxChanged), new CoerceValueCallback(CoerceMaxHeight)));

        private static object CoerceMaxHeight(DependencyObject d, object value)
        {
            TabControl tc = (TabControl)d;
            double newValue = (double)value;

            if (newValue < tc.TabItemMinHeight)
                return tc.TabItemMinHeight;

            return newValue;
        }
        #endregion

        /// <summary>
        /// OnMinMaxChanged callback responds to any of the Min/Max dependancy properties changing
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnMinMaxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                TabControl tc = (TabControl)d;
                if (tc.Template == null) return;

                VirtualizingTabPanel tp = Helper.FindVirtualizingTabPanel(tc);
                if (tp != null)
                    tp.InvalidateMeasure();
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "OnMinMaxChanged()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        /*
         * Protected override methods
         * 
        */

        /// <summary>
        /// OnApplyTemplate override
        /// </summary>
        public override void OnApplyTemplate()
        {
            try
            {
                base.OnApplyTemplate();
                this.AllowDrop = true;

                // set up the event handler for the template parts
                _toggleButton = this.Template.FindName("PART_DropDown", this) as ToggleButton;
                if (_toggleButton != null)
                {
                    // create a context menu for the togglebutton
                    ContextMenu cm = new ContextMenu();
                    cm.PlacementTarget = _toggleButton;
                    cm.Placement = PlacementMode.Bottom;

                    // create a binding between the togglebutton's IsChecked Property
                    // and the Context Menu's IsOpen Property
                    Binding b = new Binding();
                    b.Source = _toggleButton;
                    b.Mode = BindingMode.TwoWay;
                    b.Path = new PropertyPath(ToggleButton.IsCheckedProperty);

                    cm.SetBinding(ContextMenu.IsOpenProperty, b);

                    _toggleButton.ContextMenu = cm;
                    _toggleButton.Checked += DropdownButton_Checked;
                }

                ScrollViewer scrollViewer = this.Template.FindName("PART_ScrollViewer", this) as ScrollViewer;

                // set up event handlers for the RepeatButtons Click event
                RepeatButton repeatLeft = this.Template.FindName("PART_RepeatLeft", this) as RepeatButton;
                if (repeatLeft != null)
                {
                    repeatLeft.Click += delegate
                    {
                        if (scrollViewer != null)
                            scrollViewer.LineLeft();
                        GC.Collect();
                    };
                }

                RepeatButton repeatRight = this.Template.FindName("PART_RepeatRight", this) as RepeatButton;
                if (repeatRight != null)
                {
                    repeatRight.Click += delegate
                    {
                        if (scrollViewer != null)
                            scrollViewer.LineRight();
                        GC.Collect();
                    };
                }

                // set up the event handler for the 'New Tab' Button Click event
                ButtonBase button = this.Template.FindName("PART_NewTabButton", this) as ButtonBase;
                if (button != null)
                {
                    button.Click += delegate
                    {
                        TabItem item = new TabItem();
                        item.Width = 250;
                        item.MinWidth = 250;
                        item.MaxWidth = 250;

                        item.OwnerID = VMuktiAPI.VMuktiInfo.CurrentPeer.ID;
                        item.OwnerPageIndex = VMukti.App.pageCounter++;

                        ctlPgTabHeader objPgTabHeader = new ctlPgTabHeader();
                        objPgTabHeader.Title = "New Page - " + this.Items.Count.ToString();
                        //TextBlock txtBlock = new TextBlock();
                        //txtBlock.Text = "New Tab - " + this.Items.Count.ToString();

                        Image imgIcon = new Image();
                        imgIcon.Source = new BitmapImage(new Uri(@"\Controls\VMuktiGrid\Images\VMuktiIcon.ico", UriKind.RelativeOrAbsolute));
                        imgIcon.Height = 16;
                        imgIcon.Width = 16;

                        //item.Header = txtBlock;
                        item.Header = objPgTabHeader;
                        item.Icon = imgIcon;

                        item.Content = NewTabControl();


                        //if (i == -1 || i == this.Items.Count - 1 || AddNewTabToEnd)
                        this.Items.Add(item);
                        //else
                        //this.Items.Insert(++i, item);

                        if (SelectNewTabOnCreate)
                        {
                            SelectedItem = item;

                            VirtualizingTabPanel itemsHost = Helper.FindVirtualizingTabPanel(this);
                            if (itemsHost != null)
                                itemsHost.MakeVisible(item, Rect.Empty);

                            item.Focus();
                        }

                        if (TabItemAdded != null)
                            TabItemAdded(this, new TabItemEventArgs(item));
                    };
                    this.Drop += new DragEventHandler(TabControl_Drop);
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "OnApplyTemplate()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        void TabControl_Drop(object sender, DragEventArgs e)
        {
            //e.Handled = true;
            //this.AddBuddy(((VMukti.Presentation.Controls.CtlExpanderItem)e.Data.GetData(typeof(VMukti.Presentation.Controls.CtlExpanderItem))).Caption, this.SelectedIndex);
            try
            {
                e.Handled = true;

                bool blnBuddyType = true;

                if (e.Data.GetDataPresent(typeof(CtlExpanderItem)))
                {
                    #region Check whether it is module or buddy dropped

                    string[] strTag = ((CtlExpanderItem)e.Data.GetData(typeof(CtlExpanderItem))).Tag.ToString().Split(',');
                    List<string> lstTag = new List<string>();
                    for (int i = 0; i < strTag.Length; i++)
                    {
                        if (strTag[i] == "ModuleType")
                        {
                            blnBuddyType = false;
                            break;
                        }
                    }

                    #endregion

                    if (blnBuddyType && this.AddBuddy(((VMukti.Presentation.Controls.CtlExpanderItem)e.Data.GetData(typeof(VMukti.Presentation.Controls.CtlExpanderItem))).Caption, this.SelectedIndex))
                    {
                        VMuktiGrid.ctlPage.TabItem objSelectedPage = (VMuktiGrid.ctlPage.TabItem)this.SelectedItem;
                        VMuktiGrid.ctlTab.TabItem objSelectedTab = null;

                        clsPageInfo objPageInfo = new clsPageInfo();
                        objPageInfo.intPageID = ((VMuktiGrid.ctlPage.TabItem)this.SelectedItem).ObjectID;
                        objPageInfo.strPageTitle = ((VMuktiGrid.CustomMenu.ctlPgTabHeader)((VMuktiGrid.ctlPage.TabItem)this.SelectedItem).Header).Title;

                        objPageInfo.intOwnerID = VMuktiAPI.VMuktiInfo.CurrentPeer.ID;
                        objPageInfo.intOwnerPageIndex = this.SelectedIndex;

                        objPageInfo.strDropType = "OnPage";
                        List<string> lstBuddyList = new List<string>();
                        StackPanel stPageBuddyList = ((ctlMenu)((VMuktiGrid.ctlPage.TabItem)this.SelectedItem).Template.FindName("objMenu", (VMuktiGrid.ctlPage.TabItem)this.SelectedItem)).objEMIBuddyList.objBuddyList.stBuddyPanel;
                        for (int i = 0; i < stPageBuddyList.Children.Count; i++)
                        {
                            lstBuddyList.Add(((VMuktiGrid.Buddy.ctlBuddy)stPageBuddyList.Children[i]).Title);
                        }
                        objPageInfo.straPageBuddies = lstBuddyList.ToArray();


                        List<clsTabInfo> lstTabInfos = new List<clsTabInfo>();
                        for (int tCnt = 0; tCnt < ((VMuktiGrid.ctlTab.TabControl)objSelectedPage.Content).Items.Count; tCnt++)
                        {
                            objSelectedTab = ((VMuktiGrid.ctlTab.TabItem)((VMuktiGrid.ctlTab.TabControl)objSelectedPage.Content).Items[tCnt]);

                            lstTabInfos.Add(new clsTabInfo());

                            lstTabInfos[lstTabInfos.Count - 1].intTabID = objSelectedTab.ObjectID;
                            lstTabInfos[lstTabInfos.Count - 1].strTabTitle = ((VMuktiGrid.CustomMenu.ctlPgTabHeader)objSelectedTab.Header).Title;

                            StackPanel stTabBuddyList = ((ctlMenu)objSelectedTab.Template.FindName("objMenu", objSelectedTab)).objEMIBuddyList.objBuddyList.stBuddyPanel;
                            lstBuddyList.Clear();
                            for (int i = 0; i < stTabBuddyList.Children.Count; i++)
                            {
                                lstBuddyList.Add(((VMuktiGrid.Buddy.ctlBuddy)stTabBuddyList.Children[i]).Title);
                            }
                            lstTabInfos[lstTabInfos.Count - 1].straTabBuddies = lstBuddyList.ToArray();

                            lstTabInfos[lstTabInfos.Count - 1].intOwnerTabIndex = tCnt;
                            lstTabInfos[lstTabInfos.Count - 1].dblC1Width = ((VMuktiGrid.CustomGrid.ctlGrid)objSelectedTab.Content).LeftPanelContainer.ActualWidth;
                            lstTabInfos[lstTabInfos.Count - 1].dblC2Width = ((VMuktiGrid.CustomGrid.ctlGrid)objSelectedTab.Content).CentralPanelContainer.ActualWidth;
                            lstTabInfos[lstTabInfos.Count - 1].dblC3Width = ((VMuktiGrid.CustomGrid.ctlGrid)objSelectedTab.Content).RightPanelContainer.ActualWidth;

                            List<clsPodInfo> lstPodInfo = new List<clsPodInfo>();
                            VMuktiGrid.CustomGrid.ctlGrid objSelectedGrid = (VMuktiGrid.CustomGrid.ctlGrid)objSelectedTab.Content;

                            for (int pCnt = 0; pCnt < objSelectedGrid.LeftPanelContainer.Items.Count; pCnt++)
                            {
                                lstPodInfo.Add(new clsPodInfo());

                                lstPodInfo[lstPodInfo.Count - 1].intModuleId = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.LeftPanelContainer.Items[pCnt]).ModuleID;
                                lstPodInfo[lstPodInfo.Count - 1].strPodTitle = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.LeftPanelContainer.Items[pCnt]).Title;
                                lstPodInfo[lstPodInfo.Count - 1].strUri = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.LeftPanelContainer.Items[pCnt]).WCFUri;
                                lstPodInfo[lstPodInfo.Count - 1].intColumnNumber = 1;

                                lstBuddyList.Clear();
                                StackPanel stPodBuddyList = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.LeftPanelContainer.Items[pCnt]).objBuddyList.stPanel;
                                for (int i = 0; i < stPodBuddyList.Children.Count; i++)
                                {
                                    if (stPodBuddyList.Children[i].GetType() == typeof(VMuktiGrid.Buddy.ctlBuddy))
                                    {
                                        lstBuddyList.Add(((VMuktiGrid.Buddy.ctlBuddy)stPodBuddyList.Children[i]).Title);
                                    }
                                }
                                lstPodInfo[lstPodInfo.Count - 1].straPodBuddies = lstBuddyList.ToArray();
                            }

                            for (int pCnt = 0; pCnt < objSelectedGrid.CentralPanelContainer.Items.Count; pCnt++)
                            {
                                lstPodInfo.Add(new clsPodInfo());

                                lstPodInfo[lstPodInfo.Count - 1].intModuleId = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.CentralPanelContainer.Items[pCnt]).ModuleID;
                                lstPodInfo[lstPodInfo.Count - 1].strPodTitle = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.CentralPanelContainer.Items[pCnt]).Title;
                                lstPodInfo[lstPodInfo.Count - 1].strUri = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.CentralPanelContainer.Items[pCnt]).WCFUri;
                                lstPodInfo[lstPodInfo.Count - 1].intColumnNumber = 2;

                                lstBuddyList.Clear();
                                StackPanel stPodBuddyList = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.CentralPanelContainer.Items[pCnt]).objBuddyList.stPanel;
                                for (int i = 0; i < stPodBuddyList.Children.Count; i++)
                                {
                                    if (stPodBuddyList.Children[i].GetType() == typeof(VMuktiGrid.Buddy.ctlBuddy))
                                    {
                                        lstBuddyList.Add(((VMuktiGrid.Buddy.ctlBuddy)stPodBuddyList.Children[i]).Title);
                                    }
                                }
                                lstPodInfo[lstPodInfo.Count - 1].straPodBuddies = lstBuddyList.ToArray();
                            }

                            for (int pCnt = 0; pCnt < objSelectedGrid.RightPanelContainer.Items.Count; pCnt++)
                            {
                                lstPodInfo.Add(new clsPodInfo());

                                lstPodInfo[lstPodInfo.Count - 1].intModuleId = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.RightPanelContainer.Items[pCnt]).ModuleID;
                                lstPodInfo[lstPodInfo.Count - 1].strPodTitle = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.RightPanelContainer.Items[pCnt]).Title;
                                lstPodInfo[lstPodInfo.Count - 1].strUri = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.RightPanelContainer.Items[pCnt]).WCFUri;
                                lstPodInfo[lstPodInfo.Count - 1].intColumnNumber = 3;

                                lstBuddyList.Clear();
                                StackPanel stPodBuddyList = ((VMuktiGrid.CustomGrid.ctlPOD)objSelectedGrid.RightPanelContainer.Items[pCnt]).objBuddyList.stPanel;
                                for (int i = 0; i < stPodBuddyList.Children.Count; i++)
                                {
                                    if (stPodBuddyList.Children[i].GetType() == typeof(VMuktiGrid.Buddy.ctlBuddy))
                                    {
                                        lstBuddyList.Add(((VMuktiGrid.Buddy.ctlBuddy)stPodBuddyList.Children[i]).Title);
                                    }
                                }
                                lstPodInfo[lstPodInfo.Count - 1].straPodBuddies = lstBuddyList.ToArray();
                            }

                            lstTabInfos[lstTabInfos.Count - 1].objaPods = lstPodInfo.ToArray();
                        }
                        objPageInfo.objaTabs = lstTabInfos.ToArray();

                        if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.NodeWithNetP2P || VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.BootStrap || VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.SuperNode)
                        {
                            VMukti.App.chNetP2PSuperNodeChannel.svcSetSpecialMsg(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, ((VMukti.Presentation.Controls.CtlExpanderItem)e.Data.GetData(typeof(VMukti.Presentation.Controls.CtlExpanderItem))).Caption, "OPEN_PAGE", objPageInfo, VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                        }
                        else
                        {
                            try
                            {
                                VMukti.App.chHttpSuperNodeService.svcSetSpecialMsgs(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, ((VMukti.Presentation.Controls.CtlExpanderItem)e.Data.GetData(typeof(VMukti.Presentation.Controls.CtlExpanderItem))).Caption, "OPEN_PAGE", objPageInfo);
                            }
                            catch (System.ServiceModel.EndpointNotFoundException ex)
                            {
                                ex.Data.Add("My Key", "TabControl_Drop()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                                ClsException.LogError(ex);
                                ClsException.WriteToErrorLogFile(ex);
                                VMuktiAPI.VMuktiHelper.CallEvent("GetSuperNodeIP", null, null);
                                VMukti.App.chHttpSuperNodeService.svcSetSpecialMsgs(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, ((VMukti.Presentation.Controls.CtlExpanderItem)e.Data.GetData(typeof(VMukti.Presentation.Controls.CtlExpanderItem))).Caption, "OPEN_PAGE", objPageInfo);
                            }
                            catch (System.ServiceModel.CommunicationException exp1)
                            {
                                exp1.Data.Add("My Key", "TabControl_Drop()--:--TabControl.cs--:--" + exp1.Message + " :--:--");
                                ClsException.LogError(exp1);
                                ClsException.WriteToErrorLogFile(exp1);
                                VMuktiAPI.VMuktiHelper.CallEvent("GetSuperNodeIP", null, null);
                                VMukti.App.chHttpSuperNodeService.svcSetSpecialMsgs(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, ((VMukti.Presentation.Controls.CtlExpanderItem)e.Data.GetData(typeof(VMukti.Presentation.Controls.CtlExpanderItem))).Caption, "OPEN_PAGE", objPageInfo);
                            }
                        }
                        //((ctlVMuktiGrid)((Grid)((VMuktiGrid.ctlPage.TabControl)((VMuktiGrid.ctlPage.TabItem)this.Parent).Parent).Parent).Parent).fncChannelSetPageMsg(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, ((VMukti.Presentation.Controls.CtlExpanderItem)e.Data.GetData(typeof(VMukti.Presentation.Controls.CtlExpanderItem))).Caption, "OPEN_PAGE", lstModuleInfo);
                        //VMukti.App.chNetP2PSuperNodeChannel.svcAddDraggedBuddy
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "TabControl_Drop()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public ctlTab.TabControl NewTabControl()
        {
            try
            {
                ctlTab.TabControl objTabControl = new ctlTab.TabControl();
                objTabControl.SetValue(Grid.RowProperty, 1);
                objTabControl.TabItemMinWidth = 150;
                objTabControl.TabItemMaxWidth = 300;
                objTabControl.TabItemMinHeight = 30;
                objTabControl.TabItemMaxHeight = 50;
                objTabControl.VerticalAlignment = VerticalAlignment.Top;
                objTabControl.Margin = new Thickness(5);

                ctlTab.TabItem objTabItem = new ctlTab.TabItem();
                objTabItem.Width = 250;
                objTabItem.MinWidth = 250;
                objTabItem.MaxWidth = 250;
                objTabItem.OwnerTabIndex = VMukti.App.tabCounter++;
                //TextBlock txtTabBlock = new TextBlock();
                //txtTabBlock.Text = "New Tab - 0";
                ctlPgTabHeader objPgTabHeader = new ctlPgTabHeader();
                objPgTabHeader.Title = "New Tab - 0";

                Image imgTabIcon = new Image();
                imgTabIcon.Source = new BitmapImage(new Uri(@"\Controls\VMuktiGrid\Images\VMuktiIcon.ico", UriKind.RelativeOrAbsolute));
                imgTabIcon.Height = 16;
                imgTabIcon.Width = 16;

                objTabItem.Content = new CustomGrid.ctlGrid();

                //objTabItem.Header = txtTabBlock;
                objTabItem.Header = objPgTabHeader;
                objTabItem.Icon = imgTabIcon;

                objTabControl.Items.Add(objTabItem);

                LinearGradientBrush objTabItemNormalBackground = new LinearGradientBrush();
                objTabItemNormalBackground.StartPoint = new Point(0, 0);
                objTabItemNormalBackground.EndPoint = new Point(0, 1);

                objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 252, 253, 253), 0));
                objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 229, 234, 245), 0.3));
                objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 207, 215, 235), 0.3));
                objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 224, 229, 245), 0.7));
                objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 236, 238, 252), 1));

                //<GradientStop Color="#FFFBFDFE" Offset="0"/>
                //<GradientStop Color="#FFEAF6FB" Offset="0.3"/>
                //<GradientStop Color="#FFCEE7FA" Offset="0.3"/>
                //<GradientStop Color="#FFB9D1FA" Offset="1"/>

                LinearGradientBrush objTabItemSelectedBackground = new LinearGradientBrush();
                objTabItemSelectedBackground.StartPoint = new Point(0, 0);
                objTabItemSelectedBackground.EndPoint = new Point(0, 1);

                objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 251, 253, 254), 0));
                objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 234, 246, 251), 0.3));
                objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 206, 231, 250), 0.3));
                objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 185, 209, 250), 1));


                //<GradientStop Color="#FFFCFDFD" Offset="0"/>
                //<GradientStop Color="#FFC6DDF7" Offset="0.3"/>
                //<GradientStop Color="#FF99C6EE" Offset="0.3"/>
                //<GradientStop Color="#FFB6D6F1" Offset="0.7"/>
                //<GradientStop Color="#FFD9E9F9" Offset="1"/>


                LinearGradientBrush objTabItemMouseOverBackground = new LinearGradientBrush();
                objTabItemMouseOverBackground.StartPoint = new Point(0, 0);
                objTabItemMouseOverBackground.EndPoint = new Point(0, 1);

                objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 252, 253, 253), 0));
                objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 198, 221, 247), 0.3));
                objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 153, 198, 238), 0.3));
                objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 182, 214, 241), 0.7));
                objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 217, 233, 249), 1));

                objTabControl.SetValue(TabControl.pgTabItemNormalBackgroundProperty, objTabItemNormalBackground);
                objTabControl.SetValue(TabControl.pgTabItemSelectedBackgroundProperty, objTabItemSelectedBackground);
                objTabControl.SetValue(TabControl.pgTabItemMouseOverBackgroundProperty, objTabItemMouseOverBackground);

                return objTabControl;
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "NewTabControl()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return null;
            }
        }

        /// <summary>
        /// IsItemItsOwnContainerOverride
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is ctlPage.TabItem;
        }
        /// <summary>
        /// GetContainerForItemOverride
        /// </summary>
        /// <returns></returns>
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ctlPage.TabItem();
        }

        /// <summary>
        /// Handle the ToggleButton Checked event that displays a context menu of TabItem Headers
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void DropdownButton_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_toggleButton == null) return;

                _toggleButton.ContextMenu.Items.Clear();
                if (TabStripPlacement == Dock.Bottom)
                    _toggleButton.ContextMenu.Placement = PlacementMode.Top;
                else
                    _toggleButton.ContextMenu.Placement = PlacementMode.Bottom;

                for (int i = 0; i < Items.Count; i++)
                {
                    TabItem item = this.Items[i] as TabItem;
                    if (item == null)
                        return;

                    object header = Helper.CloneElement(item.Header);
                    object icon = Helper.CloneElement(item.Icon);

                    MenuItem mi = new MenuItem() { Header = header, Icon = icon, Tag = i.ToString() };
                    mi.Click += ContextMenuItem_Click;

                    _toggleButton.ContextMenu.Items.Add(mi);
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "DropdownButton_Checked()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            try
            {
                if (Items.Count == 0)
                    return;

                TabItem ti = null;

                switch (e.Key)
                {
                    case Key.Home:
                        ti = this.Items[0] as TabItem;
                        break;

                    case Key.End:
                        ti = this.Items[Items.Count - 1] as TabItem;
                        break;

                    case Key.Tab:
                        if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
                        {
                            int index = SelectedIndex;
                            int direction = 1;
                            if (e.KeyboardDevice.Modifiers == ModifierKeys.Shift)
                                direction = -1;

                            while (true)
                            {
                                index += direction;
                                if (index < 0)
                                    index = Items.Count - 1;
                                else if (index > Items.Count - 1)
                                    index = 0;

                                FrameworkElement ui = Items[index] as FrameworkElement;
                                if (ui.Visibility == Visibility.Visible && ui.IsEnabled)
                                {
                                    ti = Items[index] as TabItem;
                                    break;
                                }
                            }
                        }
                        break;
                }

                VirtualizingTabPanel panel = Helper.FindVirtualizingTabPanel(this);
                if (panel != null && ti != null)
                {
                    panel.MakeVisible(ti, Rect.Empty);
                    SelectedItem = ti;

                    e.Handled = ti.Focus();
                }
                if (!e.Handled)
                    base.OnPreviewKeyDown(e);
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "OnPreviewKeyDown()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        /// <summary>
        /// Handle the MenuItem's Click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ContextMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MenuItem mi = sender as MenuItem;
                if (mi == null) return;

                int index;
                // get the index of the TabItem from the manuitems Tag property
                bool b = int.TryParse(mi.Tag.ToString(), out index);

                if (b)
                {
                    TabItem tabItem = this.Items[index] as TabItem;
                    if (tabItem != null)
                    {
                        VirtualizingTabPanel itemsHost = Helper.FindVirtualizingTabPanel(this);
                        if (itemsHost != null)
                            itemsHost.MakeVisible(tabItem, Rect.Empty);

                        tabItem.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "ContextMenuItem_Click()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        /// <summary>
        /// Called by a child TabItem that wants to remove itself by clicking on the close button
        /// </summary>
        /// <param name="item"></param>
        internal void RemoveItem(TabItem item)
        {
            try
            {
                // gives an opertunity to cancel the removal of the tabitem
                TabItemCancelEventArgs c = new TabItemCancelEventArgs(item);
                if (TabItemClosing != null)
                    TabItemClosing(item, c);

                if (c.Cancel == true)
                    return;

                this.Items.Remove(item);

                if (TabItemClosed != null)
                    TabItemClosed(this, new TabItemEventArgs(item));
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "RemoveItem()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public bool AddBuddy(string strBuddyName, int tabItemIndex)
        {
            try
            {
                return ((ctlPage.TabItem)this.Items[tabItemIndex]).AddBuddy(strBuddyName);
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "AddBuddy()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return false;
            }
        }

        //public void LoadMeetingPage(int intOwnerID, int 

        public void LoadPage(int pageID)
        {
            try
            {
                VMukti.Business.VMuktiGrid.ClsPage objPage = VMukti.Business.VMuktiGrid.ClsPage.Get_PageInfo(pageID);

                TabItem item = new TabItem();
                item.ObjectID = pageID;
                item.IsSaved = true;
                item.OwnerID = VMuktiAPI.VMuktiInfo.CurrentPeer.ID;
                item.OwnerPageIndex = VMukti.App.pageCounter++;

                item.Width = 250;
                item.MinWidth = 250;
                item.MaxWidth = 250;

                ctlPgTabHeader objPgTabHeader = new ctlPgTabHeader();
                objPgTabHeader.Title = objPage.PageTitle;
                //TextBlock txtBlock = new TextBlock();
                //txtBlock.Text = "New Tab - " + this.Items.Count.ToString();

                Image imgIcon = new Image();
                imgIcon.Source = new BitmapImage(new Uri(@"\Controls\VMuktiGrid\Images\VMuktiIcon.ico", UriKind.RelativeOrAbsolute));
                imgIcon.Height = 16;
                imgIcon.Width = 16;

                //item.Header = txtBlock;
                item.Header = objPgTabHeader;
                item.Icon = imgIcon;

                item.Content = NewTabControl(pageID);

                //if (i == -1 || i == this.Items.Count - 1 || AddNewTabToEnd)
                this.Items.Add(item);
                //else
                //this.Items.Insert(++i, item);

                if (SelectNewTabOnCreate)
                {
                    SelectedItem = item;

                    VirtualizingTabPanel itemsHost = Helper.FindVirtualizingTabPanel(this);
                    if (itemsHost != null)
                        itemsHost.MakeVisible(item, Rect.Empty);

                    item.Focus();
                }

                if (TabItemAdded != null)
                    TabItemAdded(this, new TabItemEventArgs(item));
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "LoadPage()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public ctlTab.TabControl NewTabControl(int pageID)
        {
            try
            {
                ctlTab.TabControl objTabControl = new ctlTab.TabControl();
                objTabControl.SetValue(Grid.RowProperty, 1);
                objTabControl.TabItemMinWidth = 150;
                objTabControl.TabItemMaxWidth = 300;
                objTabControl.TabItemMinHeight = 30;
                objTabControl.TabItemMaxHeight = 50;
                objTabControl.VerticalAlignment = VerticalAlignment.Top;
                objTabControl.Margin = new Thickness(5);

                VMukti.Business.VMuktiGrid.ClsTabCollection objTabs = VMukti.Business.VMuktiGrid.ClsTabCollection.GetAll(pageID);
                foreach (VMukti.Business.VMuktiGrid.ClsTab objTab in objTabs)
                {
                    ctlTab.TabItem objTabItem = new ctlTab.TabItem();
                    objTabItem.Width = 250;
                    objTabItem.MinWidth = 250;
                    objTabItem.MaxWidth = 250;
                    objTabItem.OwnerTabIndex = VMukti.App.tabCounter++;
                    //TextBlock txtTabBlock = new TextBlock();
                    //txtTabBlock.Text = "New Tab - 0";
                    objTabItem.ObjectID = objTab.TabId;
                    objTabItem.IsSaved = true;

                    ctlPgTabHeader objPgTabHeader = new ctlPgTabHeader();
                    objPgTabHeader.Title = objTab.TabTitle;

                    Image imgTabIcon = new Image();
                    imgTabIcon.Source = new BitmapImage(new Uri(@"\Controls\VMuktiGrid\Images\VMuktiIcon.ico", UriKind.RelativeOrAbsolute));
                    imgTabIcon.Height = 16;
                    imgTabIcon.Width = 16;

                    objTabItem.Content = new CustomGrid.ctlGrid();
                    ((CustomGrid.ctlGrid)objTabItem.Content).LoadGrid(objTab.TabId);

                    //objTabItem.Header = txtTabBlock;
                    objTabItem.Header = objPgTabHeader;
                    objTabItem.Icon = imgTabIcon;

                    objTabControl.Items.Add(objTabItem);

                    LinearGradientBrush objTabItemNormalBackground = new LinearGradientBrush();
                    objTabItemNormalBackground.StartPoint = new Point(0, 0);
                    objTabItemNormalBackground.EndPoint = new Point(0, 1);

                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 252, 253, 253), 0));
                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 229, 234, 245), 0.3));
                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 207, 215, 235), 0.3));
                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 224, 229, 245), 0.7));
                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 236, 238, 252), 1));

                    //<GradientStop Color="#FFFBFDFE" Offset="0"/>
                    //<GradientStop Color="#FFEAF6FB" Offset="0.3"/>
                    //<GradientStop Color="#FFCEE7FA" Offset="0.3"/>
                    //<GradientStop Color="#FFB9D1FA" Offset="1"/>

                    LinearGradientBrush objTabItemSelectedBackground = new LinearGradientBrush();
                    objTabItemSelectedBackground.StartPoint = new Point(0, 0);
                    objTabItemSelectedBackground.EndPoint = new Point(0, 1);

                    objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 251, 253, 254), 0));
                    objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 234, 246, 251), 0.3));
                    objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 206, 231, 250), 0.3));
                    objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 185, 209, 250), 1));


                    //<GradientStop Color="#FFFCFDFD" Offset="0"/>
                    //<GradientStop Color="#FFC6DDF7" Offset="0.3"/>
                    //<GradientStop Color="#FF99C6EE" Offset="0.3"/>
                    //<GradientStop Color="#FFB6D6F1" Offset="0.7"/>
                    //<GradientStop Color="#FFD9E9F9" Offset="1"/>


                    LinearGradientBrush objTabItemMouseOverBackground = new LinearGradientBrush();
                    objTabItemMouseOverBackground.StartPoint = new Point(0, 0);
                    objTabItemMouseOverBackground.EndPoint = new Point(0, 1);

                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 252, 253, 253), 0));
                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 198, 221, 247), 0.3));
                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 153, 198, 238), 0.3));
                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 182, 214, 241), 0.7));
                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 217, 233, 249), 1));

                    objTabControl.SetValue(TabControl.pgTabItemNormalBackgroundProperty, objTabItemNormalBackground);
                    objTabControl.SetValue(TabControl.pgTabItemSelectedBackgroundProperty, objTabItemSelectedBackground);
                    objTabControl.SetValue(TabControl.pgTabItemMouseOverBackgroundProperty, objTabItemMouseOverBackground);
                }
                return objTabControl;
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "NewTabControl()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return null;
            }
        }

        public void LoadMeetingPage(clsPageInfo objPageInfo, int pageIndex)
        {
            try
            {
                VMuktiGrid.ctlPage.TabItem selectedPage = (VMuktiGrid.ctlPage.TabItem)this.Items[pageIndex];
                ((ctlPgTabHeader)selectedPage.Header).Title = objPageInfo.strPageTitle;

                int i = 0;
                int j = 0;

                for (i = 0; i < objPageInfo.objaTabs.Length; i++)
                {
                    for (j = 0; j < ((VMuktiGrid.ctlTab.TabControl)selectedPage.Content).Items.Count; j++)
                    {
                        if (((VMuktiGrid.ctlTab.TabItem)((VMuktiGrid.ctlTab.TabControl)selectedPage.Content).Items[j]).OwnerTabIndex == objPageInfo.objaTabs[i].intOwnerTabIndex)
                        {
                            ((VMuktiGrid.CustomGrid.ctlGrid)((VMuktiGrid.ctlTab.TabItem)((VMuktiGrid.ctlTab.TabControl)selectedPage.Content).Items[j]).Content).LoadMeetingGrid(objPageInfo.objaTabs[i]);
                            break;
                        }
                    }
                    if (j == ((VMuktiGrid.ctlTab.TabControl)selectedPage.Content).Items.Count)
                    {
                        ctlTab.TabItem objTabItem = new ctlTab.TabItem();
                        objTabItem.Width = 250;
                        objTabItem.MinWidth = 250;
                        objTabItem.MaxWidth = 250;
                        objTabItem.OwnerTabIndex = objPageInfo.objaTabs[i].intOwnerTabIndex;
                        //TextBlock txtTabBlock = new TextBlock();
                        //txtTabBlock.Text = "New Tab - 0";
                        objTabItem.ObjectID = int.MinValue;
                        objTabItem.IsSaved = true;

                        ctlPgTabHeader objPgTabHeader = new ctlPgTabHeader();
                        objPgTabHeader.Title = objPageInfo.objaTabs[i].strTabTitle;

                        Image imgTabIcon = new Image();
                        imgTabIcon.Source = new BitmapImage(new Uri(@"\Controls\VMuktiGrid\Images\VMuktiIcon.ico", UriKind.RelativeOrAbsolute));
                        imgTabIcon.Height = 16;
                        imgTabIcon.Width = 16;

                        objTabItem.Content = new CustomGrid.ctlGrid();
                        ((CustomGrid.ctlGrid)objTabItem.Content).LoadNewMeetingGrid(objPageInfo.objaTabs[i]);

                        //objTabItem.Header = txtTabBlock;
                        objTabItem.Header = objPgTabHeader;
                        objTabItem.Icon = imgTabIcon;

                        ((VMuktiGrid.ctlTab.TabControl)selectedPage.Content).Items.Add(objTabItem);

                        LinearGradientBrush objTabItemNormalBackground = new LinearGradientBrush();
                        objTabItemNormalBackground.StartPoint = new Point(0, 0);
                        objTabItemNormalBackground.EndPoint = new Point(0, 1);

                        objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 252, 253, 253), 0));
                        objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 229, 234, 245), 0.3));
                        objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 207, 215, 235), 0.3));
                        objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 224, 229, 245), 0.7));
                        objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 236, 238, 252), 1));

                        //<GradientStop Color="#FFFBFDFE" Offset="0"/>
                        //<GradientStop Color="#FFEAF6FB" Offset="0.3"/>
                        //<GradientStop Color="#FFCEE7FA" Offset="0.3"/>
                        //<GradientStop Color="#FFB9D1FA" Offset="1"/>

                        LinearGradientBrush objTabItemSelectedBackground = new LinearGradientBrush();
                        objTabItemSelectedBackground.StartPoint = new Point(0, 0);
                        objTabItemSelectedBackground.EndPoint = new Point(0, 1);

                        objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 251, 253, 254), 0));
                        objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 234, 246, 251), 0.3));
                        objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 206, 231, 250), 0.3));
                        objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 185, 209, 250), 1));


                        //<GradientStop Color="#FFFCFDFD" Offset="0"/>
                        //<GradientStop Color="#FFC6DDF7" Offset="0.3"/>
                        //<GradientStop Color="#FF99C6EE" Offset="0.3"/>
                        //<GradientStop Color="#FFB6D6F1" Offset="0.7"/>
                        //<GradientStop Color="#FFD9E9F9" Offset="1"/>


                        LinearGradientBrush objTabItemMouseOverBackground = new LinearGradientBrush();
                        objTabItemMouseOverBackground.StartPoint = new Point(0, 0);
                        objTabItemMouseOverBackground.EndPoint = new Point(0, 1);

                        objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 252, 253, 253), 0));
                        objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 198, 221, 247), 0.3));
                        objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 153, 198, 238), 0.3));
                        objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 182, 214, 241), 0.7));
                        objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 217, 233, 249), 1));

                        //objTabControl.SetValue(TabControl.pgTabItemNormalBackgroundProperty, objTabItemNormalBackground);
                        //objTabControl.SetValue(TabControl.pgTabItemSelectedBackgroundProperty, objTabItemSelectedBackground);
                        //objTabControl.SetValue(TabControl.pgTabItemMouseOverBackgroundProperty, objTabItemMouseOverBackground);
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "LoadMeetingPage()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public void LoadNewMeetingPage(clsPageInfo objPageInfo)
        {
            try
            {
                TabItem item = new TabItem();
                item.ObjectID = int.MinValue;
                item.IsSaved = false;
                item.OwnerID = objPageInfo.intOwnerID;
                item.OwnerPageIndex = objPageInfo.intOwnerPageIndex;

                item.Width = 250;
                item.MinWidth = 250;
                item.MaxWidth = 250;

                ctlPgTabHeader objPgTabHeader = new ctlPgTabHeader();
                objPgTabHeader.Title = objPageInfo.strPageTitle;
                //TextBlock txtBlock = new TextBlock();
                //txtBlock.Text = "New Tab - " + this.Items.Count.ToString();

                Image imgIcon = new Image();
                imgIcon.Source = new BitmapImage(new Uri(@"\Controls\VMuktiGrid\Images\VMuktiIcon.ico", UriKind.RelativeOrAbsolute));
                imgIcon.Height = 16;
                imgIcon.Width = 16;

                //item.Header = txtBlock;
                item.Header = objPgTabHeader;
                item.Icon = imgIcon;

                item.Content = NewTabControl(objPageInfo);

                if (objPageInfo.strDropType == "OnPage")
                {
                    for (int i = 0; i < objPageInfo.straPageBuddies.Length; i++)
                    {
                        item.AddBuddy(objPageInfo.straPageBuddies[i]);
                    }
                }

                //if (i == -1 || i == this.Items.Count - 1 || AddNewTabToEnd)
                this.Items.Add(item);
                //else
                //this.Items.Insert(++i, item);

                if (SelectNewTabOnCreate)
                {
                    SelectedItem = item;

                    VirtualizingTabPanel itemsHost = Helper.FindVirtualizingTabPanel(this);
                    if (itemsHost != null)
                        itemsHost.MakeVisible(item, Rect.Empty);

                    item.Focus();
                }

                if (TabItemAdded != null)
                    TabItemAdded(this, new TabItemEventArgs(item));
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "LoadNewMeetingPage()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public ctlTab.TabControl NewTabControl(clsPageInfo objPageInfo)
        {
            try
            {
                ctlTab.TabControl objTabControl = new ctlTab.TabControl();

                objTabControl.AllowAddNew = false;

                objTabControl.SetValue(Grid.RowProperty, 1);
                objTabControl.TabItemMinWidth = 150;
                objTabControl.TabItemMaxWidth = 300;
                objTabControl.TabItemMinHeight = 30;
                objTabControl.TabItemMaxHeight = 50;
                objTabControl.VerticalAlignment = VerticalAlignment.Top;
                objTabControl.Margin = new Thickness(5);

                foreach (clsTabInfo objTab in objPageInfo.objaTabs)
                {
                    ctlTab.TabItem objTabItem = new ctlTab.TabItem();
                    objTabItem.Width = 250;
                    objTabItem.MinWidth = 250;
                    objTabItem.MaxWidth = 250;
                    objTabItem.OwnerTabIndex = objTab.intOwnerTabIndex;
                    //TextBlock txtTabBlock = new TextBlock();
                    //txtTabBlock.Text = "New Tab - 0";
                    objTabItem.ObjectID = int.MinValue;
                    objTabItem.IsSaved = true;

                    ctlPgTabHeader objPgTabHeader = new ctlPgTabHeader();
                    objPgTabHeader.Title = objTab.strTabTitle;

                    Image imgTabIcon = new Image();
                    imgTabIcon.Source = new BitmapImage(new Uri(@"\Controls\VMuktiGrid\Images\VMuktiIcon.ico", UriKind.RelativeOrAbsolute));
                    imgTabIcon.Height = 16;
                    imgTabIcon.Width = 16;

                    objTabItem.Content = new CustomGrid.ctlGrid();
                    ((CustomGrid.ctlGrid)objTabItem.Content).LoadNewMeetingGrid(objTab);

                    //objTabItem.Header = txtTabBlock;
                    objTabItem.Header = objPgTabHeader;
                    objTabItem.Icon = imgTabIcon;

                    objTabControl.Items.Add(objTabItem);

                    LinearGradientBrush objTabItemNormalBackground = new LinearGradientBrush();
                    objTabItemNormalBackground.StartPoint = new Point(0, 0);
                    objTabItemNormalBackground.EndPoint = new Point(0, 1);

                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 252, 253, 253), 0));
                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 229, 234, 245), 0.3));
                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 207, 215, 235), 0.3));
                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 224, 229, 245), 0.7));
                    objTabItemNormalBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 236, 238, 252), 1));

                    //<GradientStop Color="#FFFBFDFE" Offset="0"/>
                    //<GradientStop Color="#FFEAF6FB" Offset="0.3"/>
                    //<GradientStop Color="#FFCEE7FA" Offset="0.3"/>
                    //<GradientStop Color="#FFB9D1FA" Offset="1"/>

                    LinearGradientBrush objTabItemSelectedBackground = new LinearGradientBrush();
                    objTabItemSelectedBackground.StartPoint = new Point(0, 0);
                    objTabItemSelectedBackground.EndPoint = new Point(0, 1);

                    objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 251, 253, 254), 0));
                    objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 234, 246, 251), 0.3));
                    objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 206, 231, 250), 0.3));
                    objTabItemSelectedBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 185, 209, 250), 1));


                    //<GradientStop Color="#FFFCFDFD" Offset="0"/>
                    //<GradientStop Color="#FFC6DDF7" Offset="0.3"/>
                    //<GradientStop Color="#FF99C6EE" Offset="0.3"/>
                    //<GradientStop Color="#FFB6D6F1" Offset="0.7"/>
                    //<GradientStop Color="#FFD9E9F9" Offset="1"/>


                    LinearGradientBrush objTabItemMouseOverBackground = new LinearGradientBrush();
                    objTabItemMouseOverBackground.StartPoint = new Point(0, 0);
                    objTabItemMouseOverBackground.EndPoint = new Point(0, 1);

                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 252, 253, 253), 0));
                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 198, 221, 247), 0.3));
                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 153, 198, 238), 0.3));
                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 182, 214, 241), 0.7));
                    objTabItemMouseOverBackground.GradientStops.Add(new GradientStop(Color.FromArgb(255, 217, 233, 249), 1));

                    objTabControl.SetValue(TabControl.pgTabItemNormalBackgroundProperty, objTabItemNormalBackground);
                    objTabControl.SetValue(TabControl.pgTabItemSelectedBackgroundProperty, objTabItemSelectedBackground);
                    objTabControl.SetValue(TabControl.pgTabItemMouseOverBackgroundProperty, objTabItemMouseOverBackground);
                }
                return objTabControl;
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "NewTabControl()--:--TabControl.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return null;
            }
        }
    }
}
